<?php

/**
 *Simple CRUD Code Generator
 *Email:  support@crazedcoders.com
 *Website: http://www.crazedcoders.com/
 *Copyright (C) 2007 CrazedCoders
 *
 *This program is free software: you can redistribute it and/or modify
 *it under the terms of the GNU General Public License as published by
 *the Free Software Foundation, either version 3 of the License, or
 *(at your option) any later version.
 *
 *THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *SOFTWARE.
 *
 *You should have received a copy of the GNU General Public License
 *along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * generates a php Dao for a table given the assocation returned by functions
 * like mysql_fetch_assoc or mysql_fetch_assoc, and the relativePath to
 * .include files
 */
function generateDaoForTable( $table, $relativePath ) {

	$keyColumns = array();
	//for( $i = 0; $i < sizeof( $table ); $i++ ) {
	foreach( $table as $i=>$value ) {
		if( ! is_int( $i ) )
			continue;
		if( array_key_exists(2, $table[$i] ) ) {
			array_push( $keyColumns, $table[$i][2] );
		}
	}

	$refManyTables = findRefManyColumnsFromTable( $table );

	// key combinations
	$keyCombinations = getCombinations( $keyColumns, 0 );
	//echo "keyCombinations: ";
	//var_dump( $keyCombinations );

	//$assoc = null;
	//echo "\n\ntable\n";
	//var_dump( $table );

	$primaryKey = getPKey( $table );
	$fkeys = getFKeys( $table );

	//echo "\n\nfkeys\n";
	//var_dump( $fkeys );

	$className = toCamelCase( $table[0][2]['table_name'] );
	$tableName = $table[0][2]['table_name'];
	$columns = getTableColumns( $tableName );
	$columnsString = '`'.(join('`, `',array_keys($columns))).'`';
	//$columnsString = join(', ',array_keys($columns));
	//$secondaryKeys = clone( $columns );
	$secondaryKeys = array();
	//for( $i=0; $i < sizeof( $columns ); $i++ ) {
	//	array_push( $secondaryKeys, $columns[$i] );
	//}
	foreach( $columns as $key=>$value ) {
		$secondaryKeys[$key] = toCamelCaseMember($columns[$key]);
		//$secondaryKeys[$key] = $columns[$key];
		
	}
	//$secondaryKeys = StdFunc::array_clone( $columns );
	if( isset ($primaryKey) && $primaryKey != "" ) {
		//echo "unset yes\n";
		unset( $secondaryKeys[$primaryKey] );
	}

	# create the require_once path
	$requireOnceVoPath = "";
	$splitPackage = explode( ".", con::$package );
	//echo "package: ".con::$package."<br />";
	for( $i = 0; $i < sizeof( $splitPackage ); $i++ ) {
		$requireOnceVoPath .= "../";
	}
	$requireOnceVoPath .= "vo/";
	$requireOnceVoPath .= implode( "/", $splitPackage );
	$requireOnceVoPath .= "/".$className.'.php';

	$export =
'<?php
/**
 *Simple CRUD Code Generator
 *Email:  support@crazedcoders.com
 *Website: http://www.crazedcoders.com/
 *Copyright (C) 2007 CrazedCoders
 *
 *This program is free software: you can redistribute it and/or modify
 *it under the terms of the GNU General Public License as published by
 *the Free Software Foundation, either version 3 of the License, or
 *(at your option) any later version.
 *
 *THE PROGRAM IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *SOFTWARE.
 *
 *You should have received a copy of the GNU General Public License
 *along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
require_once(\''.$requireOnceVoPath.'\');
require_once(\'./StdFunc.php\');
';
	foreach( $refManyTables as $k=>$refManyColumn ) {
		if( ! is_int( $k ) ) {
			continue;
		}
		$refTableName =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_table_name']);
		$refProperty =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_column_name']);
		$export .=
'require_once(\'./'.toCamelCase($refManyColumn['away_column'][2]
			['table_name']).'Dao.php\');
require_once(\'./'.toCamelCase($refTableName).'Dao.php\');
';


	}

	// do incoming fkeys

	foreach( $table as $tmp=>$columnassoc ) {
		if( is_int($tmp) && array_key_exists( 3, $columnassoc ) ) {
			foreach( $columnassoc[3] as $k=>$refColumn ) {
				if(
					array_key_exists( 'isManyToMany', con::$tables[
						$columnassoc[3][$k]['table_name']] )
					&&  con::$tables[$columnassoc[3][$k]['table_name']]
						['isManyToMany']) {
					continue;
				}
				$refTableName = toCamelCase(
						$refColumn['table_name'] );
				$hereMemberName = toCamelCaseMember(
						$refColumn['table_name'] );
				$export .=
'require_once(\'./'.$refTableName.'Dao.php\');
';
			}
		}
	}



	//echo "\n\nvardump( \$fkeys ) : \n"; var_dump( $fkeys );
	for( $j = 0; $j < sizeof( $fkeys ); $j++ ) {
		$refClassname = toCamelCase( $fkeys[$j]['referenced_table_name'] );
		//echo "\$refClassname : $refClassname\n";
		$export .=
'require_once(\'./'.$refClassname.'Dao.php\');
';
	}
	$export .=
'

class '.$className.'Dao {
	var $dbConn;
	static $loaded = array();

';
	//echo "\n\nvardump( \$fkeys ) : \n"; var_dump( $fkeys );
	for( $j = 0; $j < sizeof( $fkeys ); $j++ ) {
		$refClassname = toCamelCase( $fkeys[$j]['referenced_table_name'] );
		//echo "\$refClassname : $refClassname\n";
		$export .=
'	var $'.toCamelCaseMember($refClassname).'Dao;
';
	}
	$export .=
'

	public function __construct() {
		$this->dbConn = '.con::$dbtype.'_connect(
						StdFunc::$dbHost,
						StdFunc::$dbUser,
						StdFunc::$dbPass );
		'.con::$dbtype.'_select_db( StdFunc::$dbName );
';
	//echo "\n\nvardump( \$fkeys ) : \n"; var_dump( $fkeys );
	for( $j = 0; $j < sizeof( $fkeys ); $j++ ) {
		$refClassname = toCamelCase( $fkeys[$j]['referenced_table_name'] );
		//echo "\$refClassname : $refClassname\n";
		$export .=
'		$this->'.toCamelCaseMember($refClassname).'Dao = new '.
			$refClassname.'Dao();
';
	}
	$export .=
'
	}

	public function __destruct() {
		//'.con::$dbtype.'_close( $this->dbConn );
	}

	private function returnQueryRows( $rid ) {
		 /*
		ob_start();
		var_dump( debug_backtrace() );
		$tmp = ob_get_contents();
		ob_end_clean();
		StdFunc::logString("stack: ".$tmp,__CLASS__.":".__LINE__);
		 */
		$item = null;
		$results = array();
		if( ! $rid ) {
			var_dump( debug_backtrace() );
		}
		while( $assoc = '.con::$dbtype.'_fetch_assoc( $rid ) ) {
			$item = new '.$className.'();
			//$item->buniq = uniqid();
			$item->__set_state( $assoc );
';
	/*if( isset( $primaryKey ) && $primaryKey != "" ) {
		$export .=
'			'.$className.'Dao::$loaded[$item->'.$primaryKey.'] = $item;
';
	}*/
	//else {
		$export .=
'			array_push( '.$className.'Dao::$loaded, $item );
';
	//}
	$export .=
'			array_push( $results, $item );
		}
		'.con::$dbtype.'_free_result($rid);
		$this->addFKeysToObjects( $results );
		return( $results );
		//var_dump( $assoc ); // to check what the column name is
		//return( $assoc["computed"] );
	}

	private function addFKeysToObjects( $objects ) {
';

	//var_dump( $refManyTables );

	// create arrays to store
	foreach( $refManyTables as $k=>$refManyColumn ) {
		if( ! is_int( $k ) ) {
			continue;
		}
		$refTableName =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_table_name']);
		$refProperty =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_column_name']);
		$mapTableName = toCamelCase(
				$refManyColumn['away_column'][2]['table_name'] );
		$export .=
'		$dao = new '.$mapTableName.'Dao();
		$arr_'.$refTableName.'_'.$refProperty.' = array();
			//$dao->getAllBy_'
			.toCamelCaseMember($refManyColumn['home_column']
					[2]['column_name']).'( [ $'.' ] )
';
	}
	$export .=
'
		for( $j = 0; $j < sizeof( $objects ); $j++ ) {
';

	// do incoming fkeys

	foreach( $table as $tmp=>$columnassoc ) {
		if( is_int($tmp) && array_key_exists( 3, $columnassoc ) ) {
			foreach( $columnassoc[3] as $k=>$refColumn ) {
				if(
					array_key_exists( 'isManyToMany', con::$tables[
						$columnassoc[3][$k]['table_name']] )
					&&  con::$tables[$columnassoc[3][$k]['table_name']]
						['isManyToMany']) {
					continue;
				}
				$refTableName = toCamelCase(
						$refColumn['table_name'] );
				$hereMemberName = toCamelCaseMember(
						$refColumn['table_name'] );
				$export .=
'		$dao = new '.$refTableName.'Dao();
		$objects[$j]->'.toCamelCaseMember(
					$refColumn['table_name']).'s = $dao->getAllBy_'
					.toCamelCaseMember( $refColumn['column_name']).'
			(array($objects[$j]->'.toCamelCaseMember(
					   $refColumn['referenced_column_name']).'));

';
			}
		}
	}


	foreach( $refManyTables as $k=>$refManyColumn ) {
		if( ! is_int( $k ) ) {
			continue;
		}
		$refTableName =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_table_name']);
		$refProperty =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_column_name']);
		$mapTableName = toCamelCase(
				$refManyColumn['away_column'][2]['table_name'] );
				$export .=
'		$dao = new '.$mapTableName.'Dao();
';
		$export .=
'		$oids = $dao->getAllBy_'.toCamelCaseMember(
				$refManyColumn['home_column'][2]['column_name']
				).'( array( $objects[$j]->'
				.toCamelCaseMember(
				$refManyColumn['home_column'][2]['referenced_column_name']
				).' ) );
		$tmparr = array();
		foreach( $oids as $kk=>$item ) {
			array_push( $tmparr'.
					', $item->'.toCamelCaseMember(
						$refManyColumn['away_column'][2]
						['column_name']) .');
		}
		/*StdFunc::logString( "tmparr for id (".$objects[$j]->'
				.toCamelCaseMember(
				$refManyColumn['home_column'][2]['referenced_column_name'] )
					.'."):". var_export( $tmparr, true ),
				__CLASS__.":".__LINE__ );
		*/
		array_push( $arr_'.$refTableName.'_'.$refProperty.', $tmparr );
		//array_push( $arr_'.$refTableName.'_'.$refProperty.
				',$objects[$j]->'.
				toCamelCaseMember(
				$refManyColumn['home_column'][2]['referenced_column_name']
				).');
';
	}
	$export .=
'
		}
';

	$export .=
'
		for( $j = 0; $j < sizeof( $objects ); $j++ ) {
';
	for( $k = 0; $k < sizeof( $fkeys ); $k++ ) {
		$refClassname = toCamelCase( $fkeys[$k]['referenced_table_name'] );
		$refPropertyname = toCamelCaseMember(
			   $fkeys[$k]['referenced_column_name'] );
		$fkeyname = toFKeyName( $fkeys[$k]['column_name'] );
		$propertyname = toCamelCaseMember( $fkeys[$k]['column_name'] );
		//echo "propertyname : $propertyname\n";
		$export .=
'
			if( $objects[$j]->'.$propertyname.' ) {
				$tmparr = ($this->'.
					toCamelCaseMember( $refClassname).'Dao->
					getAllBy_'.$refPropertyname.'(
						array( $objects[$j]->'.$propertyname.' ) ));
				if( sizeof( $tmparr ) > 0 ) {
					$objects[$j]->'.$fkeyname.' = $tmparr[0];
				}
			}
';
	}

	foreach( $refManyTables as $k=>$refManyColumn ) {
		if( ! is_int( $k ) ) {
			continue;
		}
		$refTableName =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_table_name']);
		$refProperty =
			toCamelCaseMember(
					$refManyColumn['away_column'][2]['referenced_column_name']);
		$export .=
'			if( sizeof( $arr_'.$refTableName.'_'.$refProperty
						.'[$j] ) > 0 ) {
				$dao = new '.toCamelCase($refTableName).'Dao();
				$objects[$j]->'.$refTableName.'s = $dao->getAllBy_'
				.$refProperty.'( $arr_'.$refTableName.'_'.$refProperty
						.'[$j] );
			}
';
	}

	$export .=
'
		}
	}

	public function countAll() {
		$query =
			"SELECT COUNT(*) FROM '.$tableName.'";
		$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
		$assoc = '.con::$dbtype.'_fetch_assoc( $rid );
		//var_dump( $assoc ); // to check what the column name is
';
	if( con::$dbtype == 'mysql' ) {
		$export .=
'
		$ret = ( $assoc["COUNT(*)"] );
';
	}
	else if ( con::$dbtype== 'mssql' ) {
		$export .=
'
		$ret = ( $assoc["computed"] );
';
	}
	$export .=
'
		return( $ret );
	}

';
	if( isset( $primaryKey ) && $primaryKey != ""  ) {
		$export .=
'

	public function getAll() {
		// get the not loaded objects only
		$query =
			"SELECT '.$columnsString.' FROM '.$tableName.' ";
		$firstFlag = true;
		foreach( '.$className.'Dao::$loaded as $key=>$value) {
			if( ! $firstFlag ) {
				$query = " AND ";
			}
			$query .= " ['.$primaryKey.'] != ".$value->'.$primaryKey.';
			$firstFlag = false;
		}
		$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
		$ret = ( $this->returnQueryRows( $rid ) );

		// combine result with loaded
		//foreach( '.$className.'Dao::$loaded as $key=>$value ) {
		//	array_push( $ret, $value );
		//}
		return( '.$className.'Dao::$loaded );
	}
';
	}

	if( isset ($primaryKey) && $primaryKey != ""  ) {
		$export .=
'


	public function getAllByStartLength( $start, $length ) {
		$start = (int)$start - 1;
		$start = ($start<0)?0:$start;
		$length = (int)$length;
';
		if( con::$dbtype == 'mysql' ) {
			$export .=
'
		$query =
			"SELECT
				'.$columnsString.' FROM '.$tableName.'
				LIMIT $start, $length ;";
';
		}
		else if ( con::$dbtype == 'mssql' ) {
			$export .=
'
		$query =
			"SELECT
				TOP $length '.$columnsString.' FROM '.$tableName.'
				WHERE '.$primaryKey.' NOT IN (
					SELECT
						TOP $start '.$primaryKey.' FROM '.$tableName.'
				) ;";
';
		}
		$export .=
'
		$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
		$ret = ( $this->returnQueryRows( $rid ) );
		return( $ret );
	}

';
	}

		// generate functions per keyCombinations
		for( $i = 0; $i< sizeof( $keyCombinations ); $i++ ) {
			if( sizeof( $keyCombinations[$i] ) == 1
					&& sizeof( $keyCombinations[$i][0] ) == 0 ) {
				continue;
			}
			$export .=
'
	public function getAllBy';
			for( $j = 0; $j< sizeof( $keyCombinations[$i] ); $j++ ) {
				if ( sizeof( $keyCombinations[$i][$j] ) > 2
				  	) {
					$export .= '_'.
						toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name']);
				}
			}
			$export .= ' ( ';
			$firstFlag = false;
			for( $j = 0; $j< sizeof( $keyCombinations[$i] ); $j++ ) {
				if ( sizeof( $keyCombinations[$i][$j] ) > 1 ) {
					$export .= ($firstFlag?', $':' $').toCamelCaseMember(
							$keyCombinations[$i][$j]['column_name']);
					$firstFlag = true;
				}
			}
			$export .= ' ) {
		$query = "SELECT '.$columnsString.' FROM '.$tableName.' ";
		$whereFlag = true;
';
			for( $j = 0; $j< sizeof( $keyCombinations[$i] ); $j++ ) {
				if ( sizeof( $keyCombinations[$i][$j] ) > 2
				  	) {
					$export .=
'		/*StdFunc::logString( "'.
						toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'])
						.': " . var_export( $'.
						toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'])
						.', true
				 ) , __CLASS__.":".__LINE__ ) ;
		*/
';
				}
			}
		if( isset( $primaryKey ) && $primaryKey != ""  ) {
			$export .=
'

		// not what is already loaded
		$firstFlag = true;
		foreach( '.$className.'Dao::$loaded as $key=>$value) {
			if( ! '.$className.'Dao::$loaded[$key] )  {
				continue;
			}
			if( ! $firstFlag ) {
				$query .= " AND ";
			}
			else {
				if( $whereFlag ) {
					$query .= " WHERE ";
					$whereFlag = false;
				}
			}
			$query .= " '.$primaryKey.' != ".$value->'.$primaryKey.'." ";
			$firstFlag = false;
		}
';
		}
		else {
			$export .=
'

		$whereFlag = true;

		// not what is already loaded
		$firstFlag = true;
		foreach( '.$className.'Dao::$loaded as $key=>$value) {
			if( ! $value )  {
				continue;
			}
			if( ! $firstFlag ) {
				$query .= " AND ";
			}
			else {
				if( $whereFlag ) {
					$query .= " WHERE ";
					$whereFlag = false;
				}
				else {
					$query .= " AND ";
				}
			}
			//$query .= " '.$primaryKey.' != ".$value->'.$primaryKey.'." ";
';
			$export .=
'			$query .= " NOT ( ';
			$firstFlag = false;
			foreach( $secondaryKeys as $key=>$value )  {
				if( $firstFlag ) {
					$export .= " AND ";
				}
				$export .= '
				'.toCamelCaseMember($key).' = ".$value->'
					.toCamelCaseMember( $key ). '." ';
				//$export .= ($firstFlag?', $':' $').toCamelCaseMember(
				//		$keyCombinations[$i][$j]['column_name']);
				$firstFlag = true;
			}
			$export .= ' ) ";
			$firstFlag = false;
		}
';
		}
			$firstFlag = false;
			for( $j = 0; $j< sizeof( $keyCombinations[$i] ); $j++ ) {
				$export .=
'
		$firstFlag = false;
';
				if( sizeof( $keyCombinations[$i][$j] ) < 3 ) {
					continue;
				}
				if( $firstFlag ) {
					$export .=
'
		$query .= " AND ";
';
				}
				$export .= '
		foreach( $'.toCamelCaseMember( $keyCombinations[$i][$j]['column_name'] ).
					' as $k=>$value ) {
';
/*			$export .=
'			$query .= "'.($firstFlag?' AND ':' ' ).'";
';*/
			$export .=
'			if( ! $'.toCamelCaseMember(
			$keyCombinations[$i][$j]['column_name'] ).'[$k] ) {
				continue;
			}
			if( $firstFlag ) {
				$query .= " OR ";
			}
			else {
				if( $whereFlag ) {
					$query .= " WHERE ";
					$whereFlag = false;
				}
				else {
					$query .= " AND ";
				}
				$query .= " ( ";
			}
			$query .= "';
				if ( sizeof( $keyCombinations[$i][$j] ) > 1 ) {
					//echo "L:".__LINE__." <br />";
					$export .=
							toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'])
							.' = ".';
					if( substr_count( strtolower(
							$keyCombinations[$i][$j]['data_type']),
							'int' ) > 0 ) {
						//echo "L:".__LINE__." <br />";
						$export .= '$'.toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'] )
								. '[$k]';
						//echo "L:".__LINE__." <br />";
					}
					else if ( substr_count( strtolower(
							$keyCombinations[$i][$j]['data_type']),
							'bit' ) > 0  ) {
						//echo "L:".__LINE__." <br />";
						$export .= '".($'.toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'] )
								.'[$k]?1:0)."' ;
					}
					else {
						//echo "L:".__LINE__." <br />";
						$export .= '\$'. toCamelCaseMember(
								$keyCombinations[$i][$j]['column_name'] )
								.'[$k]';
					}
					$firstFlag = true;
				}
				$export .= ';
			$firstFlag = true;
		}
		if( $firstFlag ) {
			$query .= " ) ";
		}
';
			}



			$export .= '
		$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
		if( ! $rid ) {
			echo __CLASS__.":".__FUNCTION__.":".__LINE__."\n";
			echo "query: $query\n";
			var_dump( FundcontactDao::$loaded );
		}
		//StdFunc::logString( $query, __CLASS__.":".__LINE__ );
		$ret = ( $this->returnQueryRows( $rid ) );

		$ret = array();
		foreach( '.$className.'Dao::$loaded as $key=>$item ) {
			$condition = true;
			do {
';
			for( $j = 0; $j< sizeof( $keyCombinations[$i] ); $j++ ) {
				if( sizeof( $keyCombinations[$i][$j] ) < 2 ) {
					continue;
				}
				$propertyname = toCamelCaseMember(
						$keyCombinations[$i][$j]['column_name'] );
				$export .=
'
				$localcondition = false;
				foreach( $'.$propertyname.' as $k=>$value ) {
					StdFunc::logString( "value: $value; item->'.$propertyname
							.':"
						   .$item->'.$propertyname.', __CLASS__.":".__LINE__ );
					if( $value == $item->'.$propertyname.' ) {
						$localcondition = true;
						break;
					}
				}
				if( $localcondition == false ) {
					$condition = false;
					break;
				}
';
			}
			$export .=
'
';
			$export .=
'

			} while( false );
				StdFunc::logString( "condition; $condition" );
			if( $condition ) {
				array_push( $ret, $item );
			}
		}
		return( $ret );
';



			$export .= '
	}';
		}

	if( isset ($primaryKey) && $primaryKey != ""  ) {
		$export .=
'

	public function getOne( $primaryKey ) {
		//for( $var
		$query =
			"SELECT '.$columnsString.' FROM '.$tableName.'
				WHERE '.$primaryKey.' = $primaryKey;";
		$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
		$ret = ( $this->returnQueryRows( $rid ) );
		return( $ret[0] );
	}
';
	}

		if( isset ($primaryKey) && $primaryKey != ""  ) {
			$export .=
'

	public function updateOne( $role ) {
		$query =
			"UPDATE '.$tableName.'
				SET
';
		$firstFlag = false;
		foreach( $table as $key=>$columnassoc ) {			
			$type = $columnassoc[1];
			$value = toCamelCaseMember( $columnassoc[0] );
			
			if( substr_count( strtolower($value), 'int' ) > 0 ) {
			$export .=
'					'.($firstFlag?',':'').$value.' = ".$role->'
							.$value.'."
';
			}
			else if( $type == "tinyint" || $type == "bit") {
			$export .=
'					'.($firstFlag?',':'').$value.' = ".($role->'
							.$value.'?1:0)."
';
			}
			else if( $type == "date" || $type == "datetime")   {
			$export .=
'					'.($firstFlag?',':'').$value.' = ".date("Y-m-d",$role->'
							.$value.'/1000)."
';				
			}
			else if($value != ''){
			$export .=
'					'.($firstFlag?',':'').$value.' = \'".$role->'
							.$value.'."\'
';
			}
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'				WHERE
					'.$primaryKey.' =
						".$role->'.toCamelCaseMember($primaryKey).'.";";
		if( '.con::$dbtype.'_query( $query, $this->dbConn )  ) {
			return( true );
		}
		else {
			return( false );
		}
	}

	/// testing method
	public function test_updateOne(
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'			'.($firstFlag?',':'').'$'.toCamelCaseMember($key).'
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'	) {
		$roles = new '.$className.'();
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'		$roles->'.toCamelCaseMember($key).' = $'.$key.';
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'
		return $this->updateOne( $roles );
	}
';
		}
		$export .=
'

	public function deleteOne( $role ) {
		$query =
			"DELETE FROM '.$tableName.'
				WHERE
';
#					'.$primaryKey.' = ".$role->'.$primaryKey.'.";";

		//echo "\$table\n";
		//var_dump( $table );
	//for( $i = 0; $i<sizeof( $table ); $i++ ) {
	foreach( $table as $i=>$value ) {
		if( ! is_int($i ) ) {
			continue;
		}
		if( $i != 0 ) {
			$export.= " AND ";
		}
		$export .= $table[$i][0].' = ';
		if( substr_count( strtolower(
				$table[$i][1]),
				'int' ) > 0 ) {
			$export .= '".$role->'.toCamelCaseMember(
					$table[$i][0] ) . '."';
		}
		else if( $value[1] == "bit" ||  $value[1] == "tinytint")  {
			$export .= '".($role->'.toCamelCaseMember(
					$table[$i][0] )
					.'?1:0)."' ;
		}
		else if( $value[1] == "date" ||  $value[1] == "datetime") {
			$export .= '".date("Y-m-d",$role->'.toCamelCaseMember(
					$table[$i][0] )
					.'/1000)."' ;		
		}
		else {
			$export .= '\'".$role->'. toCamelCaseMember(
					$table[$i][0] )
					.'."\'';
		}
	}
	$export.= ";\"; ";

	$export .=
'
		return( '.con::$dbtype.'_query( $query, $this->dbConn ) );
	}

	/// testing method
	public function test_deleteOne(
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'			'.($firstFlag?',':'').'$'.toCamelCaseMember($key).'
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'	) {
		$roles = new '.$className.'();
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'		$roles->'.toCamelCaseMember($key).' = $'.$key.';
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'
		return $this->deleteOne( $roles );
	}

	public function createOne( $role ) {
		$query =
			"INSERT INTO '.$tableName.' (
';
		$firstFlag = false;
		foreach( $table as $key=>$value ) {
			if($value[0] != ''){
				$export .=
'				'.($firstFlag?',':'').$value[0].'
';
				if( ! $firstFlag ) {
					$firstFlag = true;
				}
			}
		}

		$export .=
'			)
			VALUES (
';
		$firstFlag = false;
		
		foreach( $table as $key=>$columnassoc ) {			
			$type = $columnassoc[1];
			$value = toCamelCaseMember( $columnassoc[0] );
			
			if( substr_count( strtolower($value), 'int' ) > 0 ) {
			$export .=
'					'.($firstFlag?',':'').'".$role->'
							.$value.'."
';
			}
			else if( $type == "tinyint" || $type == "bit"){
			$export .=
'					'.($firstFlag?',':'').'".($role->'
							.$value.'?1:0)."
';
			}
			else   if( $type == "date" || $type == "datetime")   {
			$export .=
'					'.($firstFlag?',':'').'".date("Y-m-d",$role->'
							.$value.'/1000)."
';				
			}
			else if($value != '') {
			$export .=
'					'.($firstFlag?',':'').'\'".$role->'
							.$value.'."\'
';
			}
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'			);";
		if( '.con::$dbtype.'_query( $query, $this->dbConn ) ) {
			$lastInsertId = null;
';
		if( con::$dbtype == 'mssql' ) {
			$export .=
'
			$query =
				"SELECT IDENT_CURRENT(\''.$tableName.'\');";
			$rid = '.con::$dbtype.'_query( $query, $this->dbConn );
			list( $lastInsertId ) = '.con::$dbtype.'_fetch_array( $rid );
';
		}
		else if ( con::$dbtype == 'mysql' ) {
			$export .=
'			$lastInsertId = '.con::$dbtype.'_insert_id( $this->dbConn );
';
		}

		if( isset ($primaryKey) && $primaryKey != ""  ) {
			$export .=
'
			$role->'.$primaryKey.' = $lastInsertId;
';
		}

		$export .=

'
			$tmparr = array();
			array_push( $tmparr, $role );
			array_push( '.$className.'Dao::$loaded, $role );
			$this->addFKeysToObjects( $tmparr );
			return( $role );
		}
		else {
			return mysql_error();
		}
	}


	/// testing method
	public function test_createOne(
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'			'.($firstFlag?',':'').'$'.toCamelCaseMember($key).'
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'	) {
		$roles = new '.$className.'();
';
		$firstFlag = false;
		foreach( $columns as $key=>$value ) {
			$export .=
'		$roles->'.toCamelCaseMember($key).' = $'.$key.';
';
			if( ! $firstFlag ) {
				$firstFlag = true;
			}
		}
		$export .=
'
		return $this->createOne( $roles );
	}

';
		# read include files
		$include =
'
		# DO NOT DELETE THIS LINE: '.con::$MARKER_STRING.'
		# USER .include CODE STARTS HERE
';
		if( file_exists( $relativePath."/".$className."Dao.include" ) ) {
			$fh = fopen( $relativePath."/".$className."Dao.include", "r" );
			if( $fh ) {
				while( ! feof( $fh ) ) {
					$include .= fread( $fh, 8192 );
				}
				fclose( $fh );
			}
		}
		else {
			$include .=
'		# USER .include FILE NOT FOUND
';
		}
		$include .=
'		# USER .include CODE ENDS HERE
';

		$export .= $include;



		$export .=
'


}

?>';

	return( $export );

}

?>
